package com.shuosen.gmall.config;

import com.alibaba.fastjson.JSON;
import com.shuosen.gmall.util.HttpClientUtil;
import io.jsonwebtoken.impl.Base64UrlCodec;
import org.apache.catalina.startup.SetAllPropertiesRule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class AuthInterceptor   extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("newToken");
        //把token保存到cookie中
        if(token!=null){
            //把token保存到cookie中
            CookieUtil.setCookie(request,response,"token",token,WebConst.cookieMaxAge,false);
            
        }
        if(token==null){
           token = CookieUtil.getCookieValue(request, "token", false);
        }
        
        if(token!=null){
            //读取token
            Map map = getUserMapByToken(token);
            String  nickName = (String) map.get("nickName");
            request.setAttribute("nickName",nickName);
        }

        HandlerMethod               handlerMethod = (HandlerMethod) handler;
        //获取请求的方法 ，并获取方法上的注解
        LoginRequire methodAnnotation = handlerMethod.getMethodAnnotation(LoginRequire.class);
        if(methodAnnotation!=null){
            //开始准备认证  verify();在passport-web中访问 跨域  @CrossOrigin  httpClient jsoup
            //httpclient  doget  dopost
            //获取salt
            String salt = request.getHeader("x-forwarded-for");
            String result = HttpClientUtil.doGet(WebConst.VERIFY_URL + "?token=" + token + "&salt=" + salt);
            if("success".equals(result)){
                //保存用户 id
                Map map = getUserMapByToken(token);
                String userId = (String) map.get("userId");
                request.setAttribute("userId",userId);
                return  true  ;
            }else{
                //还需要看一下当前注解中属性
                if(methodAnnotation.autoRedirect()){
                    //跳转登录
                    String requestUrl = request.getRequestURL().toString();
                    //进行编码
                    String encodeURL = URLEncoder.encode(requestUrl, "UTF-8");
                    //页面跳转
                     response.sendRedirect(WebConst.LOGIN_URL+"?originUrl="+encodeURL);
                     return  false;
                }
            }
        }
        return true ;
    }

    //解密token
    private Map getUserMapByToken(String token) {
        //%20eyJhbGciOiJIUzI1NiJ9.eyJuaWNrTmFtZSI6IkFkbWluaXN0cmF0b3IiLCJ1c2VySWQiOiIyIn0.CdJmODzd4Wk6nT7dBSMyJQHMwcxdZ9eTAkYu3Aw_-sE
        String ntoken = StringUtils.substringBetween(token, ".");
        //jwt通过base64编码  使用base64反解码
        Base64UrlCodec base64UrlCodec = new Base64UrlCodec();
        //字节数组
        byte[] decode = base64UrlCodec.decode(ntoken);
        //字节数组 与map集合转换 不能直接转换 将byte[] decode转换为字符串
        String mapStr = null ;
        try {
             mapStr = new String(decode,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map map  = JSON.parseObject(mapStr,Map.class);
        return map;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
